package cn.zwx.strategy.pattern.example.strategy;

import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;


/**
 * @projectName:strategy-pattern-example
 * @see:cn.zwx.strategy.pattern.example.strategy
 * @author:zhangwenxue
 * @createTime:2022/2/11 10:31
 * @version:1.0
 */
@Service
public class StrategyService {

    @Resource
    private GrantTypeService grantTypeService;

    private Map<String, Function<String,String>> grantTypeMap =new ConcurrentHashMap<>(8);

    /**
     *  初始化业务分派逻辑,代替了if-else部分
     *  key: 优惠券类型
     *  value: lambda表达式,最终会获得该优惠券的发放方式
     */
    @PostConstruct
    public void dispatcherInit(){
        grantTypeMap.put("红包",resourceType->grantTypeService.redPaper());
        grantTypeMap.put("购物券",resourceType->grantTypeService.shopping());
        grantTypeMap.put("QQ会员",resourceType->grantTypeService.qqVip());
        grantTypeMap.put("外卖会员",resourceType->grantTypeService.takeOutVip());
    }

    public String getResult(String resourceType){
        Function<String,String> result = grantTypeMap.get(resourceType);
        if(Objects.nonNull(result)){
            return result.apply(resourceType);
        }
        return "查询不到该优惠券的发放方式";
    }

}
